//
//  ChatViewController.m
//  leo
//
//  Created by 常艳 on 15/10/4.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ChatViewController.h"
#import "ReceiveTableViewCell.h"
#import "SendTableViewCell.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "RecordViewController.h"
#import "SyncManager.h"
#import "AppDelegate.h"
#import "SyncManager.h"
#import "VoiceConverter.h"
@import AVFoundation;
@import AudioToolbox;
@interface ChatViewController ()

@property(nonatomic,strong) NSArray *chatArray;//聊天数据
@property(nonatomic,assign) int chatNums;
@property(nonatomic,assign) int limitNums;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) User *user;
@property(nonatomic,assign) BOOL isRegis;
@property(nonatomic,strong) NSMutableDictionary *nameLists;
@property(nonatomic,strong) NSMutableDictionary *picLists;
@property(nonatomic,strong) NSMutableDictionary *isWatchLists;
@property(nonatomic,strong) NSMutableDictionary *watchGenderLists;
@property(nonatomic,strong)  UIWindow *keyWindow;
@property(nonatomic,strong)  UIWindow *alertView;
@property(nonatomic,assign) BOOL isAdd;
@property(nonatomic,strong) RecordViewController *recordView;
@property(nonatomic,strong) SyncManager *syncManager;
@property(nonatomic,assign) BOOL isCancle;
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,weak) AppDelegate *mydelegate;
@property(nonatomic,assign) float rate;
@property(nonatomic,assign) CGPoint previous;
@property(nonatomic,assign) int gender;//和手表聊天时，表示宝宝性别
@end

@implementation ChatViewController
-(void)dealloc
{
    [self.alertView removeFromSuperview];
    self.alertView.rootViewController=NULL;
    [self.recordView removeFromParentViewController];
    [self removeObservers];
    self.chatArray=NULL;
    self.dataManager=NULL;
    self.nameLists=NULL;
    self.picLists=NULL;
    self.isWatchLists=NULL;
    self.watchGenderLists=NULL;
    self.keyWindow=NULL;
    self.alertView=NULL;
    self.recordView=NULL;
    self.syncManager=NULL;
    self.timer=NULL;
    self.mydelegate=NULL;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.rate=[UIScreen mainScreen].bounds.size.width/375;
    CGRect rect=CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y, self.tableView.frame.size.width*self.rate, self.tableView.frame.size.height*self.rate);
    self.tableView.frame=rect;
    self.isRegis=NO;
    self.isAdd=NO;
    self.isCancle=NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.alertView=[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, 375*self.rate, 518*self.rate)];
    self.recordView=[[RecordViewController alloc]init];
    self.keyWindow = [[[UIApplication sharedApplication] delegate] window];
    [self.recordView setMotherWindow:self.alertView];
    self.alertView.rootViewController=self.recordView;
    [self.keyWindow addSubview:self.alertView];
    [self.alertView setWindowLevel:UIWindowLevelAlert];
    
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,dataManager is null.",chat_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 12"];
        return;
    }
    self.syncManager=[[SyncManager alloc] init];
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,syncManager is null.",chat_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 13"];
        return;
    }
    self.user=[User sharedSingleton];
    if(self.user==NULL)
    {
        NSLog(@"%@,viewDidLoad,user is null.",chat_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 14"];
        return;
    }
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    if(self.mydelegate==NULL)
    {
        NSLog(@"%@,viewDidLoad,mydelegate is null.",chat_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 15"];
        return;
    }
    self.mydelegate.lastTimeStamp=0;
    [self registerObservers];
    //获取登录帐号详细信息
    self.nameLists=[[NSMutableDictionary alloc] init];
    self.picLists=[[NSMutableDictionary alloc] init];
    self.isWatchLists=[[NSMutableDictionary alloc] init];
    self.watchGenderLists=[[NSMutableDictionary alloc] init];
    if(self.nameLists==NULL||self.picLists==NULL)
    {
        NSLog(@"%@,viewDidLoad,nameLists or picLists is null.",chat_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 16"];
        return;
    }
    self.limitNums=10;
    [self loadChatData];
    [self loadChatNums];
    [self loadChats];
    [self setChatView];
    if([self.chatArray count]>0)
      [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1   inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    

    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    //[self setRead];
}
-(void)loadChatData
{
    Watch *selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    if(selectWatch==NULL)
        return;
    Manager *owner=[self.dataManager gettheManager:self.user.uid accountId:self.user.uid deviceUid:selectWatch.deviceUid];
    if(owner==NULL)
    {
        NSLog(@"%@,viewDidLoad,owner is null.",chat_tag);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    [self.nameLists removeAllObjects];
    [self.picLists removeAllObjects];
    if(user.nickName!=NULL&&![user.nickName isEqualToString:@"(null)"]&&![user.nickName isEqualToString:@""])
    {
        [self.nameLists setValue:user.nickName forKey:user.uid];
    }
    else
    {
        [self.nameLists setValue:owner.nickName forKey:owner.user_id];
    }
    if(user.pic_url!=NULL&&![user.pic_url isEqualToString:@"(null)"]&&![user.pic_url isEqualToString:@""])
    {
        [self.picLists setValue:user.pic_url forKey:user.uid];
    }
    else
    {
        [self.picLists setValue:owner.pic_url forKey:owner.user_id];
    }
    if(self.type==1)//家庭圈聊天
    {
        self.title=@"家庭圈";
        //获取家庭圈所有成员信息
        NSArray *watchList=[self.dataManager getGroupWatchList:[selectWatch.groupId intValue]];
        if(watchList==NULL||[watchList count]==0)
            return;
        NSArray *managers=[self.dataManager getGroupManagers:self.groupId accountId:self.user.uid deviceUid:selectWatch.deviceUid];
        if(managers!=NULL&&[managers count]>0)
        {
            for(int i=0;i<[managers count];i++)
            {
                Manager *theManager=[managers objectAtIndex:i];
                if(theManager==NULL)
                {
                    NSLog(@"%@,viewDidLoad,theManager is null,index is %d.",chat_tag,i);
                    continue;
                }
                [self.nameLists setValue:theManager.nickName forKey:theManager.user_id];
                [self.picLists setValue:theManager.pic_url forKey:theManager.user_id];
            }
        }
        //获取手表详细信息
        for(int i=0;i<[watchList count];i++)
        {
            Watch *watch=[watchList objectAtIndex:i];
            if(watch==NULL)
                return;
            [self.nameLists setValue:watch.nickname forKey:watch.deviceUid];
            [self.picLists setValue:watch.pic_url forKey:watch.deviceUid];
            [self.isWatchLists setValue:@"1" forKey:watch.deviceUid];
            [self.watchGenderLists setValue:[NSString stringWithFormat:@"%d",watch.gender] forKey:watch.deviceUid];
        }

    }
    else if(self.type==2)//和手表聊天
    {
        //获取手表详细信息
        Watch *watch=[self.dataManager getWatch:self.deviceUid];
        self.gender=watch.gender;
        if(watch!=NULL)
        {
            [self.nameLists setValue:watch.nickname forKey:watch.deviceUid];
            [self.picLists setValue:watch.pic_url forKey:watch.deviceUid];
            if(watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"]&&[watch.nickname length]>0)
            {
                self.title=watch.nickname;
            }
            else
            {
                self.title=@"宝宝";
            }
            
        }


    }
    else if(self.type==3)//和其他副管理员聊天
    {
        //获取单聊对方详细信息
        Manager *partner=[self.dataManager gettheManager:self.managerId accountId:self.user.uid deviceUid:selectWatch.deviceUid];
        if(partner!=NULL)
        {
            [self.nameLists setValue:partner.nickName forKey:partner.user_id];
            [self.picLists setValue:partner.pic_url forKey:partner.user_id];
        }
        if(partner.nickName!=NULL&&![partner.nickName isEqualToString:@"(null)"]&&[partner.nickName length]>0)
        {
            self.title=partner.nickName;
        }
        else
        {
            if([Tooler getManagerType:partner.type]==ADMIN)
            {
                self.title=@"主管理员";
            }
            else
            {
                self.title=@"副管理员";
            }
            
        }
     
    }

}
-(void)loadChatNums
{
    if(self.type==1)
    {
        if(self.dataManager!=NULL)
        {
            self.chatNums=[self.dataManager getAllGroupChatNums:self.groupId accountId:self.user.uid];
        }
    }
    else if(self.type==2)
    {
        if(self.dataManager!=NULL)
        {
            self.chatNums=[self.dataManager getAllSingleChatNums:self.deviceUid myId:self.user.uid];
        }
    }
    else if(self.type==3)
    {
        if(self.dataManager!=NULL)
        {
            self.chatNums=[self.dataManager getAllSingleChatNums:self.managerId myId:self.user.uid];
        }
    }
}
-(void)loadChats
{
    self.chatArray=NULL;
    self.mydelegate.lastTimeStamp=0;
    if(self.type==1)
    {
        if(self.dataManager!=NULL)
        {
            self.chatArray=[self.dataManager getChatLists:self.groupId accountId:self.user.uid limit:self.limitNums];
        }
    }
    else if(self.type==2)
    {
        if(self.dataManager!=NULL)
        {
            self.chatArray=[self.dataManager getSingleChatLists:self.deviceUid myId:self.user.uid limit:self.limitNums];
        }
    }
    else if(self.type==3)
    {
        if(self.dataManager!=NULL)
        {
            self.chatArray=[self.dataManager getSingleChatLists:self.managerId myId:self.user.uid limit:self.limitNums];
        }
    }
    [self handleChatData];

}
-(void)handleChatData
{
    for (int i=(int)([self.chatArray count]-1); i>=0; i--) {
        Chat *chat=[self.chatArray objectAtIndex:i];
        if(chat==NULL||chat.genTime==NULL)
            continue;
        chat.showTime=YES;
        if(abs((int)(self.mydelegate.lastTimeStamp-[chat.genTime longLongValue]))/60<5)
        {
            self.mydelegate.lastTimeStamp=(long)[chat.genTime longLongValue];
            chat.showTime=NO;
        }
        self.mydelegate.lastTimeStamp=(long)[chat.genTime longLongValue];
    }
}
-(void)setRead
{
    if(self.type==1)
    {
        if(self.dataManager!=NULL)
        {
            [self.dataManager setGroupChatRead:self.groupId accountId:self.user.uid];
        }
    }
    else if(self.type==2)
    {
        if(self.dataManager!=NULL)
        {
            [self.dataManager setSingleChatRead:self.deviceUid accountId:self.user.uid];
        }
    }
    else if(self.type==3)
    {
        if(self.dataManager!=NULL)
        {
            [self.dataManager setSingleChatRead:self.managerId accountId:self.user.uid];
        }
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.chatArray==NULL)
    {
        return 0;
    }
    else
    {
        return self.chatArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(!self.isRegis)
    {
        [tableView registerNib:[UINib nibWithNibName:@"SendTableViewCell" bundle:nil] forCellReuseIdentifier: @"SendTableViewCell"];
        [tableView registerNib:[UINib nibWithNibName:@"ReceiveTableViewCell" bundle:nil] forCellReuseIdentifier:@"ReceiveTableViewCell"];
        self.isRegis=YES;
    }
    NSInteger row=[indexPath row];
    Chat *chat=[self.chatArray objectAtIndex:[self.chatArray count]-row-1];
    if(chat==NULL)
    {
        NSLog(@"%@,cellForRowAtIndexPath,chat is null.",chat_tag);
        return nil;
    }

    if([chat.user_id intValue]==[self.user.uid intValue])
    {
        SendTableViewCell *cell=(SendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"SendTableViewCell"];
        if(self.picLists!=NULL)
        {
            NSString *pic_url=[self.picLists valueForKey:chat.user_id];
            if(pic_url!=NULL&&![pic_url isEqualToString:@"(null)"]&&![pic_url isEqualToString:@""]&&[[pic_url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>1)
            {
                NSString *pic_path=[[Tooler getDocumentDirectory] stringByAppendingString:pic_url];
                cell.headImg.image=[UIImage imageNamed:pic_path];
            }
        }
        cell.chat=chat;
        cell.type=self.type;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell initData];
        [cell initUI];
        return cell;
    }
    else
    {
        ReceiveTableViewCell *cell=(ReceiveTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ReceiveTableViewCell"];
        if(self.nameLists!=NULL)
        {
            NSString *name=[self.nameLists valueForKey:chat.user_id];
            if(name!=NULL&&![name isEqualToString:@"(null)"])
            {
               cell.nameLable.text=name; 
            }
            else
            {

            }
            
        }
        if(self.picLists!=NULL)
        {
            NSString *pic_url=[self.picLists valueForKey:chat.user_id];
            if(pic_url!=NULL&&![pic_url isEqualToString:@"(null)"]&&![pic_url isEqualToString:@""]&&[[pic_url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]>1)
            {
                cell.headImg.image=[UIImage imageNamed:pic_url];
            }
            else
            {
                if(self.type==1)//家庭圈
                {
                    NSString *isWatch=[self.isWatchLists valueForKey:chat.user_id];
                    if(isWatch!=NULL&&[isWatch isEqualToString:@"1"])//是手表
                    {
                        NSString *watchGender=[self.watchGenderLists valueForKey:chat.user_id];
                        if(watchGender!=NULL&&[watchGender isEqualToString:@"1"])//女孩
                        {
                            cell.headImg.image=[UIImage imageNamed:@"avater_girl.png"];
                        }
                        else
                        {
                            cell.headImg.image=[UIImage imageNamed:@"avater_boy.png"];
                        }
                    }
                    else
                    {
                        cell.headImg.image=[UIImage imageNamed:@"avater_other.png"];
                    }
                }
                else if(self.type==2)//手表
                {
                    if(self.gender==1)//女孩
                    {
                        cell.headImg.image=[UIImage imageNamed:@"avater_girl.png"];
                    }
                    else
                    {
                        cell.headImg.image=[UIImage imageNamed:@"avater_boy.png"];
                    }
                }
                else
                {
                   cell.headImg.image=[UIImage imageNamed:@"avater_other.png"];
                }

            }
        }
        if(chat.duration>0)
        {
            cell.durationLable.text=[NSString stringWithFormat:@"%d''",chat.duration];
        }

        cell.recordPath=chat.file_url;
        cell.chatId=chat.chatId;
        if(chat.showTime==YES&&chat.genTime!=NULL&&![chat.genTime isEqualToString:@"(null)"])
        {
            cell.timeLable.text=[Tooler getDateTime:chat.genTime];
        }
        else
        {
            cell.timeLable.text=@"";
        }
        if(chat.is_read==0)
            chat.is_read=[self.dataManager isChatRead:chat.chatId];
        cell.isRead=chat.is_read;
        if(chat.is_read==0)
        {
            cell.unreadImg.hidden=NO;
        }
        else
        {
            cell.unreadImg.hidden=YES;
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell initUI];
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Chat *chat=[self.chatArray objectAtIndex:[self.chatArray count]-[indexPath row]-1];
    if(chat.showTime&& chat!=NULL&&chat.genTime!=NULL)
    {
        return 90*self.rate;
    }
    else
    {
        if([chat.user_id isEqualToString:self.user.uid])
            return 65.0*self.rate;
        else
            return 75.0*self.rate;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}
-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{

    if ( scrollView.frame.size.height-scrollView.contentOffset.y > scrollView.frame.size.height + 50)
    {
        [self loadChatNums];
        if(self.limitNums<self.chatNums)
        {
            self.limitNums=self.limitNums+5;
            [self loadChats];
            [self.tableView reloadData];
        }
    }
  
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch=[touches anyObject];
    CGPoint current=[touch locationInView:self.view];
    if(CGRectContainsPoint(self.recordBtn.frame, current))
    {

        [self startRecord];
        self.previous=current;
    }
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch=[touches anyObject];
    CGPoint current=[touch locationInView:self.view];
    //CGPoint previous=[touch previousLocationInView:self.view];
    if(self.previous.y -current.y>50)
    {
        [self preCancleRecord];
        self.recordView.isCancle=YES;
        self.previous=current;
    }
    if(current.y-self.previous.y>50)
    {
        [self preSendRecord];
        self.recordView.isCancle=NO;
        self.previous=current;
    }
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(!self.isAdd)
        return;
    if(!self.isCancle)
    {
        [self stopRecord];
    }
    else
    {
        [self cancleRecord];
    }
}
-(void)startRecord
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate.sendCell!=NULL)
    {
        [mydelegate.sendCell stop];
        mydelegate.sendCell=NULL;
    }
    if(mydelegate.receiveCell!=NULL)
    {
        [mydelegate.receiveCell stop];
        mydelegate.receiveCell=NULL;
    }
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    if(!self.isAdd)
    {
        self.isAdd=YES;
        int res=[self.recordView start];
        if(res==-1)
        {
            self.isAdd=NO;
            return;
        }
        [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"record_button1_press@2x.png"] forState:UIControlStateNormal];
        [self.recordBtn setTitle:@"松开 结束" forState:UIControlStateNormal];
        [self.recordBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.recordView.infoLable.text=@"手指上滑，取消发送";
        self.isAdd=YES;

        [self.alertView makeKeyAndVisible];


    }

}

- (void)stopRecord {
    [self.recordBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
    [self.recordBtn setTitleColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1] forState:UIControlStateNormal];
    [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"record_button1_normal@2x.png"] forState:UIControlStateNormal];
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    self.isAdd=NO;
    [self.recordView stop];
    //录制时间太短
    if([self.recordView getDuration]<1)
    {
        //[self.recordView stop];
        self.recordView.infoLable.text=@"录音时间太短";
        self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
        return;
    }

    self.alertView.hidden=YES;
    NSString *file_url=[self.recordView getRecordFilePath];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",record_tag);
        return;
    }
    NSString *send_url=[self.recordView getRecordSendPath];
    if(send_url==NULL)
        return;
    if(![VoiceConverter ConvertWavToAmr:file_url amrSavePath:send_url])
        return;
    Chat *chat=[[Chat alloc] init];
    //chat.file_url=file_url;
    chat.type=0;
    if(self.type==1)
    {
       chat.groupId=self.groupId;//家庭圈
    }
    else if(self.type==2)
    {
        chat.targetUid=self.deviceUid;//给手表
    }
    else if(self.type==3)
    {
        chat.targetUid=self.managerId;//给其他副管理员
    }
    chat.file_name=[self.recordView getRecordFileName];
    chat.amr_name=[self.recordView getRecordSendName];
    chat.genTime=[Tooler getTS];
    chat.duration=[self.recordView getDuration];
    chat.user_id=self.user.uid;
    chat.accountId=self.user.uid;
    chat.is_read=1;
    chat.is_finish=1;
    chat.is_send=0;
    [self.dataManager addChat:chat];
    [self loadChats];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1   inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
}
-(void)timeDown
{
     self.alertView.hidden=YES;
    [self.timer invalidate];
}
-(void)preSendRecord
{
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    self.recordView.infoLable.text=@"手指上滑，取消发送";
    UIImage *sendImg=[UIImage imageNamed:@"record_anim0@2x"];
    self.recordView.actionImg.image=sendImg;
    sendImg=NULL;
}
- (void)preCancleRecord {
    self.isCancle=YES;
    self.recordView.isCancle=YES;
    self.recordView.infoLable.text=@"松开手指，取消发送";
    self.recordView.actionImg.image=[UIImage imageNamed:@"record_Trash@2x"];
}
- (void)cancleRecord {
    [self.recordBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
    [self.recordBtn setTitleColor:[UIColor colorWithRed:178/255.0 green:178/255.0 blue:178/255.0 alpha:1] forState:UIControlStateNormal];
    [self.recordBtn setBackgroundImage:[UIImage imageNamed:@"record_button1_normal@2x.png"] forState:UIControlStateNormal];
    self.alertView.hidden=YES;
    self.isAdd=NO;
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    [self.recordView stop];
    NSString *file_url=[self.recordView getRecordFilePath];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",record_tag);
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        NSLog(@"%@,cancleRecord,delete file error,error is %@.",chat_tag,err);
    }
}
-(void)setChatView
{
    if(self.dataManager==NULL)
        return;
    if(self.type==1)
    {
        [self.dataManager setGroupChatView:self.groupId];
    }
    else if(self.type==2)
    {
        [self.dataManager setSingleChatView:self.deviceUid];
    }
    else if(self.type==3)
    {
        [self.dataManager setSingleChatView:self.managerId];
    }
}
-(void)registerObservers
{

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:SYNCCHATDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:RECORDTIMEEXCEED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:MANAGERPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNotification:)
                                                 name: RESENDCHATSUCESS
                                               object: nil];
}
-(void)removeObservers
{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:SYNCCHATDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RECORDTIMEEXCEED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MANAGERPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RESENDCHATSUCESS object:nil];
}
- (void)receiveNotification:(NSNotification *)sender {

    if([sender.name isEqualToString:SYNCCHATDATAFINISHED])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadChats];
            [self.tableView reloadData];
            if([self.chatArray count]>0)
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.chatArray count]-1   inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [self setChatView];
        });
    }
    else if([sender.name isEqualToString:RECORDTIMEEXCEED])
    {
        [self stopRecord];
    }
    else if([sender.name isEqualToString:USERINFOUPDATE])
    {
        [self loadChatData];
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:MANAGERPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadChatData];
            [self.tableView reloadData];
        });

    }
    else if([sender.name isEqualToString:WATCHPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadChatData];
            [self.tableView reloadData];
        });

    }
    else if([sender.name isEqualToString:RESENDCHATSUCESS])
    {
        [self.tableView reloadData];
    }


}
@end
